#include "HttpManager.h"
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QEventLoop>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>

HttpManager::HttpManager()
{
}

QByteArray HttpManager::accessResult(const QString &url, const QHash<QString,QString> header, const AccessType type, const QJsonObject &obj/*for post*/, const QHash<QString, QString> cookie){
    QNetworkAccessManager manager;
    QNetworkRequest request;
    QNetworkReply * reply;
    QEventLoop loop;
    QObject::connect(&manager,SIGNAL(finished(QNetworkReply*)),&loop,SLOT(quit()));

    request.setUrl(QUrl(url));

    for (auto it = header.begin(); it != header.end(); ++it){
        request.setRawHeader(it.key().toUtf8(),it.value().toUtf8());
    }

    QString cookieStr;
    for (auto it = cookie.begin(); it != cookie.end(); ++it) {
        cookieStr += it.key() + "=" + it.value() + ";";
    }
    if (cookieStr.endsWith(";")) {
        cookieStr = cookieStr.mid(0,cookieStr.size() -1);
    }

    QByteArray retBody = QJsonDocument(obj).toJson();
    retBody = retBody.replace("\n","").replace(" ","");

    cookieStr = QUrl::fromPercentEncoding(cookieStr.toUtf8());

    request.setRawHeader("Cookie",cookieStr.toUtf8());

    request.setUrl(QUrl(url));

    if (type == GET) {
        reply = manager.get(request);
    } else if (type == POST) {
        QString length = QString::number(retBody.length());
        qDebug() << retBody << length;
        request.setRawHeader("Content-Length",length.toUtf8());
        reply = manager.post(request,retBody);
    } else {
        qDebug()<<"error";
    }

    loop.exec();
    QByteArray result = reply->readAll();
    reply->deleteLater();
    return result;
}
